"use strict";
var express = require('express');
var ejs = require('ejs-mate');
var path = require('path');
var app = express();

var ueditor = require("ueditor");
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

var index = require('./routes/index');
var users = require('./routes/users');
var admin = require('./routes/admin')

var article = require('./routes/article');
var feedback = require('./routes/feedback');
var member =  require('./routes/member');
var picture =  require('./routes/picture');
var product =  require('./routes/product')
var admin = require('./routes/admin');

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
// view engine setup
app.use(cookieParser());


app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));

app.engine('.html', ejs);
app.set('view engine', 'html');


app.use("/ueditor/ue", ueditor(path.join(__dirname, 'public'), function (req, res, next) {
    //客户端上传文件设置
    var imgDir = '/img/ueditor/'
     var ActionType = req.query.action;
    if (ActionType === 'uploadimage' || ActionType === 'uploadfile' || ActionType === 'uploadvideo') {
        var file_url = imgDir;//默认图片上传地址
        /*其他上传格式的地址*/
        if (ActionType === 'uploadfile') {
            file_url = '/file/ueditor/'; //附件
        }
        if (ActionType === 'uploadvideo') {
            file_url = '/video/ueditor/'; //视频
        }
        res.ue_up(file_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
        res.setHeader('Content-Type', 'text/html');
    }
    //  客户端发起图片列表请求
    else if (req.query.action === 'listimage') {
        var dir_url = imgDir;
        res.ue_list(dir_url); // 客户端会列出 dir_url 目录下的所有图片
    }
    // 客户端发起其它请求
    else {
        // console.log('config.json')
        res.setHeader('Content-Type', 'application/json');
        res.redirect('/ueditor/nodejs/config.json');
    }
}));

app.use('/', index);
app.use('/users', users);
app.use('/article',article);

app.use('/feedback',feedback);
app.use('/member',member);

app.use('/picture',picture);
app.use('/product',product);
app.use('/admin',admin);


module.exports = app;
